<?php
namespace app\admin\controller;

use think\Cache;
use think\Controller;
use think\Request;
use think\Db;
use think\cache\Driver;

class System extends Common
{
	/**
	 * 菜单列表
	 * */
	public function menuList()
	{
		$input = Request()->param();
		$pid = $input['pid'] ? $input['pid'] : 0;

		$where['pid'] = $pid;
		$list = Db::name('menu')->where($where)->order('sort asc')->select();
		$this->assign('list', $list);

		$this->assign('title', '菜单列表');

		return $this->fetch();
	}

	/**
	 * 菜单排序
	 * */
	public function saveSort()
	{
		if (Request()->isPost()) {
			$input = Request()->param();

			$sortObj = json_decode($input['sortObj'], true);
			$res = model('menu')->saveAll($sortObj);
			if ($res) {
				Cache::clear();
				renewTopAndGroupUrl();

				adminReturn(1, '更新排序成功');
			} else {
				adminReturn(2, '更新排序失败');
			}
		}
	}

	/**
	 * 新增/编辑 菜单
	 * */
	public function doMenu()
	{
		if (Request()->isPost()) {
			$input = Request()->param();

			$pid = $input['pid'] ? $input['pid'] : 0;
			$id = $input['id'];
			$name = $input['name'];
			$icon = $input['icon'] ? $input['icon'] : '';
			$url = $input['url'] ? $input['url'] : '';
			$sort = $input['sort'] ? $input['sort'] : 0;
			$is_show = $input['is_show'];
			$level = $input['level'] ? $input['level'] : 1;

			if (empty($name)) adminReturn(2, '请输入菜单名');

			$data = [
				'pid' => $pid,
				'name' => $name,
				'level' => $level,
				'sort' => $sort,
				'is_show' => $is_show
			];
			if ($level == 2) {
				$data['icon'] = $icon;
			} else if ($level == 3) {
				$data['url'] = $url;
			} else if ($level == 4) {
				$data['url'] = $url;
				$data['is_show'] = 2;
			}

			if ($id > 0) {
				$data['update_time'] = time();

				$res = Db::name('menu')->where(['id' => $id])->update($data);
				if ($res) {
					Cache::clear();

					if ($level == 3 || $level == 2) renewTopAndGroupUrl();

					adminReturn(1, '编辑菜单成功', url('menuList', ['level' => $level, 'pid' => $pid]));
				} else {
					adminReturn(2, '编辑菜单失败');
				}
			} else {
				$data['create_time'] = time();

				$res = Db::name('menu')->insert($data);
				if ($res) {
					Cache::clear();
					if ($level == 3 || $level == 2) renewTopAndGroupUrl();

					adminReturn(1, '新增菜单成功', url('menuList', ['level' => $level, 'pid' => $pid]));
				} else {
					adminReturn(2, '新增菜单失败');
				}
			}
		} else {
			$input = Request()->param();
			$id = $input['id'] ? $input['id'] : 0;

			if ($id > 0) {
				$info = Db::name('menu')->where(['id' => $id])->find();
				$this->assign('info', $info);

				$this->assign('title', '编辑菜单');
			} else {
				$this->assign('title', '新增菜单');
			}

			return $this->fetch();
		}
	}

	/**
	 * 删除菜单
	 * */
	public function delMenu()
	{
		$id = Request()->param('id');
		$pid = Request()->param('pid');
		$level = Request()->param('level');

		if ($id) {
			$res = Db::name('menu')->where(['id' => $id])->delete();
			if ($res) {
				Cache::clear();
				if ($level == 3 || $level == 2) renewTopAndGroupUrl();

				adminReturn(1, '删除菜单成功', url('menuList', ['level' => $level, 'pid' => $pid]));
			} else {
				adminReturn(2, '删除菜单失败');
			}
		} else {
			adminReturn(2, '菜单ID缺失', url('menuList', ['level' => $level, 'pid' => $pid]));
		}
	}

	/**
	 * 配置分组列表
	 * */
	public function configGroupList()
	{
		$configGroup = $this->getConfigGroup();

		$this->assign('list', $configGroup);

		$this->assign('title', '配置分组');
		return $this->fetch();
	}

	/**
	 * 新增/编辑 分组
	 * */
	public function doConfigGroup()
	{
		if(Request()->isPost()){
			$input = Request()->param();

			$id = $input['id'];
			$name = $input['name'];
			$sort = $input['sort'] ? $input['sort'] : 0;

			if(empty($name)) adminReturn(2, '请输入分组名');

			$map['name'] = $name;
			if($id) $map['id'] = ['neq', $id];
			$count = Db::name('config_group')->where($map)->count();
			if($count > 0) adminReturn(2, '该分组已存在');

			$data = [
				'name' => $name,
				'sort' => $sort
			];
			if($id){
				$data['update_time'] = time();

				$res = Db::name('config_group')->where(['id' => $id])->update($data);
				if($res){
					Cache::clear();

					adminReturn(1, '编辑分组成功', url('configGroupList'));
				}else{
					adminReturn(2, '编辑分组失败');
				}
			}else{
				$data['create_time'] = time();

				$res = Db::name('config_group')->insert($data);
				if($res){
					Cache::clear();

					adminReturn(1, '新增分组成功', url('configGroupList'));
				}else{
					adminReturn(2, '新增分组失败');
				}
			}
		}else{
			$input = Request()->param();
			$id = $input['id'] ? $input['id'] : 0;

			if ($id > 0) {
				$info = Db::name('config_group')->where(['id' => $id])->find();
				$this->assign('info', $info);

				$this->assign('title', '编辑配置');
			} else {
				$this->assign('title', '新增配置');
			}
			return $this->fetch();
		}
	}

	/**
	 * 删除配置分组
	 * */
	public function delConfigGroup()
	{
		$id = Request()->param('id');

		if ($id) {
			$res = Db::name('config_group')->where(['id' => $id])->delete();
			if ($res) {
				Cache::clear();

				adminReturn(1, '删除配置分组成功', url('configGroupList'));
			} else {
				adminReturn(2, '删除配置分组失败');
			}
		} else {
			adminReturn(2, '配置分组ID缺失', url('configGroupList'));
		}
	}

	/**
	 * 菜单排序
	 * */
	public function saveConfigGroupSort()
	{
		if (Request()->isPost()) {
			$input = Request()->param();

			$sortObj = json_decode($input['sortObj'], true);
			$res = model('config_group')->saveAll($sortObj);
			if ($res) {
				Cache::clear();

				adminReturn(1, '更新排序成功');
			} else {
				adminReturn(2, '更新排序失败');
			}
		}
	}

	/**
	 * 网站设置
	 * */
	public function setConfig()
	{
		if(Request()->isPost()){
			$input = Request()->post();

			if($input){
				$data = [];
			    foreach($input as $k => $v){
					$single = [];
				    $single['id'] = $k;
				    $single['value'] = $v;
				    $data[] = $single;
			    }

				$res = model('config')->saveAll($data);
			    if($res){
			    	Cache::clear();

				    adminReturn(1, '保存成功');
			    }else{
				    adminReturn(2, '保存失败');
			    }
			}else{
				adminReturn(2, '保存失败');
			}
		}else{
			$id = Request()->param('id') ? Request()->param('id') : 1;
			$this->assign('id', $id);

			$this->assign('title', '网站设置');
			return $this->fetch();
		}
	}

	/**
	 * 新增/编辑 配置
	 * */
	public function doConfig()
	{
		if(Request()->isPost()){
			$input = Request()->param();

			$id = $input['id'];
			$title = $input['title'];
			$name = $input['name'];
			$value = $input['value'];
			$type = $input['type'];
			$group_id = $input['group_id'];
			$sort = $input['sort'];
			$remark = $input['remark'];

			if(empty($title)) adminReturn(2, '请输入配置标题');
			if(empty($name)) adminReturn(2, '请输入配置标识');
			if(empty($value)) adminReturn(2, '请输入配置值');

			if($id) $map['id'] = ['neq', $id];
			$title_count = Db::name('config')->where(['title' => $title])->where($map)->count();
			$name_count = Db::name('config')->where(['name' => $name])->where($map)->count();

			if($title_count > 0) adminReturn(2, '配置标题已存在');
			if($name_count > 0) adminReturn(2, '配置标识已存在');

			$data = [
				'title' => $title,
				'name' => $name,
				'value' => $value,
				'type' => $type,
				'group_id' => $group_id,
				'sort' => $sort,
				'remark' => $remark
			];

			if($id){
				$res = Db::name('config')->where(['id' => $id])->update($data);
				if($res){
					Cache::clear();

					adminReturn(1,'编辑配置成功',url('setConfig'));
				}else{
					adminReturn(2,'编辑配置失败');
				}
			}else{
				$res = Db::name('config')->insert($data);
				if($res){
					Cache::clear();

					adminReturn(1,'新增配置成功',url('setConfig'));
				}else{
					adminReturn(2,'新增配置失败');
				}
			}
		}else{
			$input = Request()->param();
			$id = $input['id'] ? $input['id'] : 0;

			if ($id > 0) {
				$info = Db::name('config')->where(['id' => $id])->find();
				$this->assign('info', $info);

				$this->assign('title', '编辑配置');
			} else {
				$this->assign('title', '新增配置');
			}
			return $this->fetch();
		}
	}

	/**
	 * 网站配置排序
	 * */
	public function saveConfigSort()
	{
		if (Request()->isPost()) {
			$input = Request()->param();

			$sortObj = json_decode($input['sortObj'], true);
			$res = model('config')->saveAll($sortObj);
			if ($res) {
				Cache::clear();

				adminReturn(1, '更新排序成功');
			} else {
				adminReturn(2, '更新排序失败');
			}
		}
	}

	/**
	 * 删除配置
	 * */
	public function delConfig()
	{
		$input = Request()->param();

		$id = $input['id'];
		if(empty($id)) adminReturn(2, '配置ID缺失');

		$info = Db::name('config')->where(['id' => $id])->find();
		if($info){
			$res = Db::name('config')->where(['id' => $id])->delete();
			if($res){
				Cache::clear();

				adminReturn(1, '删除成功', url('setConfig'));
			}else{
				adminReturn(2, '删除失败');
			}
		}else{
			adminReturn(2, '配置不存在或已删除');
		}
	}

	/**
	 * 用户信息
	 * */
	public function userList()
	{
		$list = Db::name('user')->paginate();
		$this->assign('list', $list);

		$this->assign('title', '用户信息');
		return $this->fetch();
	}

	/**
	 * 权限分组列表
	 * */
	public function authGroupList()
	{
		$list = Db::name('auth_group')->select();
		$this->assign('list', $list);

		$this->assign('title', '权限分组列表');
		return $this->fetch();
	}

	/**
	 * 新增/编辑 权限分组
	 * */
	public function doAuthGroup()
	{
		if(Request()->isPost()){
			$input = Request()->post();

			$id = $input['id'];
			$name = $input['name'];
			$desc = $input['desc'];

			if(empty($name)) adminReturn(2,'请输入分组名');

			$map['name'] = $name;
			if($id) $map['id'] = ['neq', $id];
			$count = Db::name('auth_group')->where($map)->count();
			if($count) adminReturn(2, '该分组名已存在');

			$data = [
				'name' => $name,
				'desc' => $desc
			];

			if($id){
				$res = Db::name('auth_group')->where(['id' => $id])->update($data);
				if($res){
					adminReturn(1, '编辑权限分组成功', url('authGroupList'));
				}else{
					adminReturn(2, '编辑权限分组失败');
				}
			}else{
				$res = Db::name('auth_group')->insert($data);
				if($res){
					adminReturn(1, '新增权限分组成功', url('authGroupList'));
				}else{
					adminReturn(2, '新增权限分组失败');
				}
			}
		}else{
			$id = Request()->param('id');

			if($id){
				$info = Db::name('auth_group')->where(['id' => $id])->find();
				$this->assign('info', $info);

				$this->assign('title', '编辑权限分组');
			}else{
				$this->assign('title', '新增权限分组');
			}
			return $this->fetch();
		}
	}

	/**
	 * 启用 / 禁用
	 * */
	public function doAuthGroupStatus()
	{
		$id = Request()->param('id');

		if(empty($id)) adminReturn(2, '分组ID缺失');

		$info = Db::name('auth_group')->where(['id' => $id])->find();
		if($info){
			$status = $info['status'] == 1 ? 2 : 1;

			$res = Db::name('auth_group')->where(['id' => $id])->setField('status', $status);
			if($res){
				Cache::clear();

				adminReturn(1, '操作成功', url('authGroupList'));
			}else{
				adminReturn(2, '操作失败');
			}
		}else{
			adminReturn(2, '分组不存在或已删除');
		}
	}

	/**
	 * 删除权限分组
	 * */
	public function delAuthGroup()
	{
		$id = Request()->param('id');

		if ($id) {
			$res = Db::name('auth_group')->where(['id' => $id])->delete();
			if ($res) {
				Cache::clear();

				adminReturn(1, '删除权限分组成功', url('authGroupList'));
			} else {
				adminReturn(2, '删除权限分组失败');
			}
		} else {
			adminReturn(2, '权限分组ID缺失', url('authGroupList'));
		}
	}

	/**
	 * 访问授权
	 * */
	public function visit()
	{
		if(Request()->isPost()){
			$input = Request()->post();

			$id = $input['id'];//权限分组id
			$ids = $input['ids'];

			if(empty($id)) adminReturn(2, '权限分组ID缺失');
			if(empty($ids)) adminReturn(2, '请选择授权模块');
			if(!in_array(1, $ids)) adminReturn(2, '首页必须授权');

			$rules = $ids;
		    foreach($ids as &$v){
			    getNoCheckParentId($v, $rules);
		    }

		    $data = [
		    	'show_rules' => implode(',', $ids),
			    'rules' => implode(',', $rules),
			    'update_time' => time()
		    ];
			$res = Db::name('auth_group')->where(['id' => $id])->update($data);
			if($res){
				Cache::clear();

				adminReturn(1, '保存成功');
			}else{
				adminReturn(2, '保存失败');
			}
		}else{
			$this->assign('title', '访问授权');
			return $this->fetch();
		}
	}

	/**
	 * 用户授权
	 * */
	public function userAuth()
	{
		$input = Request()->param();

		$id = $input['id'];

		$list = Db::name('auth_group_access')->alias('a')->join('user u', 'a.uid = u.id')->field('u.id uid,u.account,u.username')->where(['a.group_id' => $id])->select();
		$this->assign('list', $list);

		$this->assign('title', '用户授权');
		return $this->fetch();
	}

	public function test()
	{
		getUserAuthMenuId();
	}

	/**
	 * 新增授权
	 * */
	public function addAuth()
	{
		$input = Request()->param();

		$uid = str_replace('，', ',', $input['uid']);
		$uid_arr = explode(',', $uid);

		$group_id = $input['group_id'];

		if(empty($uid)) adminReturn(2, '请输入UID');
		if(empty($group_id)) adminReturn(2, '分组ID缺失');
		if(count($uid_arr) == 1){
			if(intval($uid) === 1){
				adminReturn(2, '该用户为超级管理员');
			}elseif(intval($uid) > 1){
				$user_count = Db::name('user')->where(['id' => $uid])->count();
				if($user_count == 0) adminReturn(2, '用户不存在');

				$auth_count = Db::name('auth_group_access')->where(['uid' => $uid, 'group_id' => $group_id])->count();
				if($auth_count) adminReturn(2, '该权限分组已添加该账号，请勿重新添加');
			}else{
				adminReturn(2, '输入的UID有误，请重新输入');
			}
		}

	    foreach($uid_arr as &$v){
			if($v > 1){
				$count = Db::name('auth_group_access')->where(['uid' => $v, 'group_id' => $group_id])->count();
				if($count == 0){
					$res = Db::name('auth_group_access')->insert(['uid' => $v, 'group_id' => $group_id]);
					if($res){
						$password = Db::name('user')->where(['id' => $v])->column('password');
						if($password[0] == ''){
							Db::name('user')->where(['id' => $v])->setField('password', thinkEncrypt(123456));
						}
					}
				}
			}
	    }

	    adminReturn(1, '新增权限成功');
	}

	/**
	 * 解除授权
	 * */
	public function relieveAuth()
	{
		$input = Request()->param();

		$uid = $input['uid'];
		$group_id = $input['group_id'];

		if(empty($uid)) adminReturn(2, 'UID缺失');
		if(empty($group_id)) adminReturn(2, '分组ID缺失');

		$res = Db::name('auth_group_access')->where(['uid' => $uid, 'group_id' => $group_id])->delete();
		if($res){
			adminReturn(1, '解除授权成功');
		}else{
			adminReturn(2, '解除授权失败');
		}
	}


}
